<template>
  <!-- 修改容器背景为渐变色 -->
  <div
    id="container"
    class="text-white text-sm bg-primary-300 min-h-screen pb-4"
  >
    <Header />
    <div class="flex items-center justify-center px-4">
      <div class="w-full" style="max-width: 1440px">
        <!-- 主内容卡片 -->
        <div class="bg-white rounded-xl shadow-2xl mt-6 overflow-hidden">
          <!-- 书籍头部信息区 -->
          <div class="flex flex-col md:flex-row p-6 gap-6 border-b">
            <!-- 封面区域增加光影效果 -->
            <div class="md:w-1/4 relative group">
              <div
                class="rounded-xl overflow-hidden shadow-lg relative w-full"
                style="padding-top: 125%"
              >
                >
                <div class="absolute inset-0">
                  <img
                    v-if="book.cover_image_url"
                    :src="book.cover_image_url"
                    alt="封面"
                    class="w-full h-full object-cover"
                  />
                  <img
                    v-else
                    src="../assets/images/default_cover.jpg"
                    alt="默认封面"
                    class="w-full h-full object-cover filter grayscale-20"
                  />
                </div>
              </div>
              <!-- 收藏按钮增加动效 -->
              <button
                @click="collect_or_cancle(book.id)"
                :class="
                  collectStatus
                    ? 'bg-red-500 hover:bg-red-600'
                    : 'bg-blue-500 hover:bg-blue-600'
                "
                class="mt-4 w-full py-2 text-white rounded-lg transition-all duration-300 transform hover:shadow-lg hover:-translate-y-1"
              >
                {{ collectMessage }}
              </button>
            </div>

            <!-- 书籍信息区域增加排版层次 -->
            <div class="md:w-3/4 space-y-4">
              <h1 class="text-3xl font-bold text-gray-800">{{ book.name }}</h1>
              <div class="space-y-2 text-gray-600">
                <div class="flex items-center">
                  <i class="fas fa-user-pen mr-2 text-blue-500 w-5"></i>
                  <span class="text-lg">作者：{{ book.user_name }}</span>
                </div>
                <div class="flex items-center">
                  <i class="fas fa-tag mr-2 text-green-500 w-5"></i>
                  <span class="text-lg">分类：{{ book.category_name }}</span>
                </div>
                <div class="flex items-center">
                  <i class="fas fa-clock mr-2 text-purple-500 w-5"></i>
                  <span class="text-lg"
                    >更新时间：{{ formatDateTime(book.update_time) }}</span
                  >
                </div>
              </div>
            </div>
          </div>

          <!-- 简介区域增加装饰线 -->
          <div class="p-6 border-b">
            <h2
              class="text-xl font-semibold text-gray-800 mb-4 relative pl-3 before:absolute before:left-0 before:top-1/2 before:-translate-y-1/2 before:w-1 before:h-6 before:bg-blue-500"
            >
              作品简介
            </h2>
            <p class="text-gray-600 leading-7 text-justify indent-8">
              {{ book.review || "暂无简介" }}
            </p>
          </div>

          <!-- 章节列表优化 -->
          <div class="p-6">
            <h2
              class="text-xl font-semibold text-gray-800 mb-6 relative pl-3 before:absolute before:left-0 before:top-1/2 before:-translate-y-1/2 before:w-1 before:h-6 before:bg-green-500"
            >
              最新章节
            </h2>
            <div v-if="articles.length" class="space-y-2">
              <router-link
                v-for="(article, index) in articles"
                :key="article.id"
                :to="`/book/${book.id}/article/${article.id}`"
                class="flex justify-between items-center p-4 rounded-lg hover:bg-blue-50 transition-colors group border"
              >
                <div class="flex items-center">
                  <span class="w-8 text-gray-400 font-mono"
                    >{{ index + 1 }}.</span
                  >
                  <span
                    class="text-gray-700 group-hover:text-blue-600 transition-colors"
                  >
                    {{ article.title }}
                  </span>
                </div>
                <span class="text-sm text-gray-400">{{
                  formatShortDate(article.create_time)
                }}</span>
              </router-link>
            </div>
            <div v-else class="text-center py-8 text-gray-400">
              <i class="fas fa-inbox text-3xl mb-2"></i>
              <p>暂无章节内容</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script>
import axios from "axios";
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import showMessage from "@/utils/message.js";

export default {
  name: "BookDetail",
  data() {
    return {
      book: {},
      articles: [], // 章节数据
      collectStatus: false,
      collectMessage: "",
    };
  },
  components: { Header, Footer },
  mounted() {
    this.get_book_info();
    this.fetchArticles(); // 调用获取章节
    // 判断一下用户是否登录
    if (!this.$store.state.isLogin) {
      this.collectStatus = false;
      this.collectMessage = "添加收藏";
    } else {
      const book_id = this.$route.params.id;
      this.get_collect_status(book_id);
    }
  },
  methods: {
    get_book_info: function () {
      axios
        .get(`/api/book/${this.$route.params.id}/`)
        .then((response) => (this.book = response.data));
    },
    // 获取收藏状态
    get_collect_status(book_id) {
      axios
        .get("/api/collect/" + book_id + "/is_collected/")
        .then((response) => {
          this.collectStatus = response.data.is_collected;
          if (this.collectStatus) {
            this.collectMessage = "取消收藏";
          } else {
            this.collectMessage = "添加收藏";
          }
        });
    },
    // 收藏或取消收藏
    collect_or_cancle(book_id) {
      if (!this.$store.state.isLogin) {
        showMessage("请先登录", "error", () => {
          this.$router.push({
            name: "Login",
          });
        });
        return;
      }
      if (this.collectStatus) {
        this.cancle_collect_book(book_id);
      } else {
        this.collect_book(book_id);
      }
    },
    // 收藏书籍
    collect_book(book_id) {
      axios
        .post("/api/collect/", { book_id: book_id })
        .then((response) => {
          const status_code = response.data.status_code;
          const message = response.data.message;
          if (status_code === 0) {
            this.collectStatus = true;
            this.collectMessage = "取消收藏";
            showMessage(message, "info");
          } else {
            showMessage(message, "error");
          }
        })
        .catch((error) => {
          showMessage("收藏失败");
        });
    },
    // 取消收藏
    cancle_collect_book(book_id) {
      axios
        .delete("/api/collect/" + book_id + "/")
        .then((response) => {
          const status_code = response.data.status_code;
          const message = response.data.message;
          if (status_code === void 0) {
            this.collectStatus = false;
            this.collectMessage = "添加收藏";
            showMessage(message, "info");
          } else {
            showMessage(message);
          }
        })
        .catch((error) => {
          showMessage("取消收藏失败");
        });
    },
    // 获取章节
    fetchArticles() {
      axios
        .get(`/api/article/?book=${this.$route.params.id}`)
        .then((response) => {
          this.articles = response.data;
        })
        .catch((error) => {
          console.error("获取章节失败:", error);
          this.articles = [];
        });
    },
    // 日期格式化
    formatDateTime(dateString) {
      const options = {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      };
      return new Date(dateString).toLocaleString("zh-CN", options);
    },
    formatShortDate(dateString) {
      return new Date(dateString).toLocaleDateString("zh-CN", {
        month: "2-digit",
        day: "2-digit",
      });
    },
  },
};
</script>

<style>
/* 添加自定义字体图标样式 */
@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css");
.fas {
  display: inline-block;
  text-align: center;
  font-size: 1.1em; /* 确保图标尺寸合适 */
  width: 1.25rem; /* 对齐w-5类 (1.25rem = 20px) */
}
</style>
